package com.xnet.common.utils;

import com.xnet.common.entity.TreeGridEntity;
import java.util.List;
import java.util.stream.Collectors;

/*
   构造树形表格Json
 */
public  class TreeGridJson {

    public static int lft = 1, rgt = 1000000;
    /// <summary>
    /// 转换树形Json
    /// </summary>
    /// <param name="list">数据源</param>
    /// <param name="ParentId">父节点</param>
    /// <returns></returns>
    public static String TreeJson(List<TreeGridEntity> ListData, int index, String ParentId)
    {
        StringBuilder sb = new StringBuilder();
        List<TreeGridEntity> ChildNodeList = ListData.stream().filter(x->x.getParentId().equals(ParentId)).collect(Collectors.toList());
        if (ChildNodeList.size() > 0) { index++; }
        for(TreeGridEntity entity : ChildNodeList)
        {
            String entityJson=entity.getEntityJson();
            StringBuilder strJson = new StringBuilder(entityJson);
            String isLeaf=String.valueOf(!entity.getHasChildren());
            strJson = strJson.insert(1, "\"level\":" + index + ",");
            strJson = strJson.insert(1, "\"isLeaf\":" + isLeaf + ",");
            strJson = strJson.insert(1, "\"expanded\":" +String.valueOf(entity.isExpanded()).toLowerCase() + ",");
            strJson = strJson.insert(1, "\"lft\":" + lft++ + ",");
            strJson = strJson.insert(1, "\"rgt\":" + rgt-- + ",");
            sb.append(strJson);
            sb.append(TreeJson(ListData, index, entity.getId()));
        }
        return sb.toString().replace("}{", "},{");
    }
    /// <summary>
    /// 转换树形Json
    /// </summary>
    /// <param name="list">数据源</param>
    /// <returns></returns>
    public static String TreeJson(List<TreeGridEntity> ListData)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("{ \"rows\": [");
        sb.append(TreeJson(ListData, -1, "0"));
        sb.append("]}");
        return sb.toString();
    }
}
